package com.study.animationstudy.ui

import android.annotation.SuppressLint
import android.graphics.drawable.AnimationDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import com.study.animationstudy.R
import com.study.animationstudy.base.BaseActivity
import com.study.animationstudy.databinding.ActivityFrameAnimBinding

/**
 * 帧动画是实现原理最简单的一种，跟现实生活中的电影胶卷类似，都是在短时间内连续播放多张图片，从而模拟动态画面的效果。
 * @property animationDrawable AnimationDrawable
 */
class FrameAnimActivity : BaseActivity<ActivityFrameAnimBinding>(),OnClickListener {

    lateinit var animationDrawable: AnimationDrawable

    override fun ActivityFrameAnimBinding.initBinding() {
        mBinding.ivFrameAnim.setOnClickListener(this@FrameAnimActivity)
        animationDrawable = AnimationDrawable()
        showFrameAnimByCode()
//        showFrameAnimByXml()
    }

    /**
     * 代码方式显示帧动画
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    fun showFrameAnimByCode(){
        //帧动画需要把每帧图片加入AnimationDrawable队列
        animationDrawable.apply {
            //添加一幅图片帧，并指定该帧的持续时间（单位毫秒）。
            addFrame(resources.getDrawable(R.drawable.flow_p1,this@FrameAnimActivity.theme),50)
            addFrame(resources.getDrawable(R.drawable.flow_p2,this@FrameAnimActivity.theme),50)
            addFrame(resources.getDrawable(R.drawable.flow_p3,this@FrameAnimActivity.theme),50)
            addFrame(resources.getDrawable(R.drawable.flow_p4,this@FrameAnimActivity.theme),50)
            addFrame(resources.getDrawable(R.drawable.flow_p5,this@FrameAnimActivity.theme),50)
            addFrame(resources.getDrawable(R.drawable.flow_p6,this@FrameAnimActivity.theme),50)
            addFrame(resources.getDrawable(R.drawable.flow_p7,this@FrameAnimActivity.theme),50)
            addFrame(resources.getDrawable(R.drawable.flow_p8,this@FrameAnimActivity.theme),50)
            //setOneShot为true表示只播放一次，为false表示循环播放
            isOneShot = false
            mBinding.ivFrameAnim.setImageDrawable(this)
            start()
        }
    }

    /**
     * xml方式启动帧动画
     */
    fun showFrameAnimByXml(){
        mBinding.ivFrameAnim.setImageResource(R.drawable.frame_anim)
        animationDrawable = mBinding.ivFrameAnim.drawable as AnimationDrawable
        animationDrawable.start()
    }

    override fun onClick(v: View?) {
        v?.let {
            when(v.id){
                mBinding.ivFrameAnim.id -> {
                    if(animationDrawable.isRunning){
                        animationDrawable.stop()
                    } else {
                        animationDrawable.start()
                    }
                }
            }
        }
    }

}